package com.example.demo.service;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import com.example.common.streams.LogStreams;
import com.example.common.utility.JdbcUtility;
import com.example.demo.model.TestLog;

@Service
public class ServiceErrorLogCreateOperation implements CreateOperation<Integer, Long> {
	@Autowired
	private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

	@Override
	public Long create(Integer id) {
		var log = new TestLog();

		log.setValue(id);
		log.setCreateTime(LocalDateTime.now());
		log.setUpdateTime(LocalDateTime.now());

		var keyHolder = new GeneratedKeyHolder();

		namedParameterJdbcTemplate.update(JdbcUtility.getInsertSql(log, "id"),
				JdbcUtility.getSqlParameterSource(log, "id"), keyHolder);

		return keyHolder.getKey().longValue();
	}

	@StreamListener(value = LogStreams.LOG_SERVICE_TOPIC_INPUT, condition = "headers['partitionKey']=='service-error-logs'")
	public void handle(@Payload Integer id) {
		this.create(id);
	}

}
